//设置默认根路径
axios.defaults.baseURL = 'http://ajax-api.itheima.net'

//设置一个渲染函数
const renderList = async () => {
  //1.发起顶级分类的请求
  const { data: res } = await axios({ url: '/api/category/top' })

  //提取数据
  const { data } = res
  //2.发起二级分类的请求
  const requests = data.map(item => axios({ url: '/api/category/sub', params: { id: item.id } }))

  //   console.log(requests)
  //3.使用Promise.all集中式发起请求
  const newData = await Promise.all(requests)
  //   console.log(newData)

  //4.对请求获得的数据进行解构处理
  const subData = newData.map(item => {
    const {
      data: { data },
    } = item
    return data
  })

  console.log(subData)

  //5.开始渲染真实dom
  const htmlStr = subData
    .map(item => {
      return `<!-- 基础模板 -->
    <li>
      <a href="javascript:;">${item.name}</a>
      <img
        src="${item.picture}"
        alt=""
      />
      <ul class="sub">
      ${item.children
        .map(item => {
          return `<li>
        <a href="javascript:;">
          <span>${item.name}</span>
          <img
            src="${item.picture}"
            alt=""
          />
        </a>
      </li>`
        })
        .join('')}
      </ul>
    </li>`
    })
    .join('')

  document.querySelector('.top').innerHTML = htmlStr
}

//调用渲染函数
renderList()
